import 'package:fast_build/common/theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:hk_base/hk_base.dart';

/// App主体风格
enum ThemeStyle { light, dark }

/// 为枚举扩展类型为字符串的value属性
extension HkThemeStyleExtension on ThemeStyle {
  String get value => ['light', 'dark'][index];
}

class ThemeUtil {

  /// 切换主题
  static changeTheme() {
    ThemeMode mode = getLocalThemeModel();
    ThemeData themeData = getLocalThemeData();
    EasyLoadingStyle easyLoadingStyle = EasyLoadingStyle.dark;
    if (mode == ThemeMode.dark) {
      easyLoadingStyle = EasyLoadingStyle.light;
      HkCache.setString('current_theme', ThemeStyle.light.value);
    } else if (mode == ThemeMode.light) {
      easyLoadingStyle = EasyLoadingStyle.dark;
      HkCache.setString('current_theme', ThemeStyle.dark.value);
    }

    EasyLoading.instance.loadingStyle = easyLoadingStyle;
    Get.changeThemeMode(mode);
    Get.changeTheme(themeData);

    //这里设置这个延迟原因是：在调用切换主题后，无法立即生效，会有一些延迟，如果不延迟会读取还是上个主题
    //使用Get 强制更新app状态
    Future.delayed(const Duration(milliseconds: 300), () {
      HkLog.d(
          "执行这里:\nisDarkMode${Get.isDarkMode}\ncurrentStyle:${HkCache.getString('current_theme')}\neasyLoadingStyle:$easyLoadingStyle");
      Get.forceAppUpdate();
      hkShowToast("换肤成功${HkCache.getString('current_theme')}~");
    });
  }

  /// 获取本地 主题配置
  static getLocalThemeModel() {
    //读取是否是暗黑模式
    ThemeMode themeMode = ThemeMode.light;
    if (HkCache.getString('current_theme') != null) {
      String? theme = HkCache.getString('current_theme');
      HkLog.d("currentStyle:$theme");
      if (theme == ThemeStyle.dark.value) {
        themeMode = ThemeMode.dark;
      } else {
        themeMode = ThemeMode.light;
      }
    }
    HkLog.d("themeMode:$themeMode");
    return themeMode;
  }

  static getLocalThemeData() {
    //读取是否是暗黑模式
    String? theme = HkCache.getString('current_theme');
    ThemeData themeData = ThemeData.light();
    if (theme != null && theme == ThemeStyle.dark.value) {
      if (!Get.isDarkMode) {
        themeData = LightThemeStyle();
      } else {
        themeData = DarkThemeStyle();
      }
    } else {
      themeData = LightThemeStyle();
    }
    return themeData;
  }
}
